I have an object as an input with a structure like this:(basically a simple nested object)
const test ={
id: "0000",
parent1 : "foo",
parent2: { child1: "data1",
child2: "data2",
child3: "data3"
},
parent3: { child1: "data1",
child2: "data2",
child3: "data3"
}
}
This test object has some empty values, and the purpose of the code is to loop through the object and find properties with values.
const update = {};
for(const key in test){
if(test[key] !== ""){
update[key] = test[key];
console.log(update);
}
};
The loop works just fine finding them. But when it finds a child, it saves it like this, as an example, {child: "data2"} and won't save the parent's name.
How is possible to modify this code and avoid too many if/else conditions, basically an optimized code, when having an object like this:
{
id: "foo",
parent1 : Null,
parent2: { child1: Null,
child2: "data2",
child3: Null
},
parent3: { child1: Null,
child2: Null,
child3: "data3"
}
}
A result like this:
{ id: "foo", parent2.child2: "data2", parent3.child3: "data3"]
or more likely something like this:
{ id: "foo", parent2:{child2: "data2"}, parent3:{child3: "data3"}}